'use strict';

const { Controller } = require('egg');
const { Op } = require('sequelize');
const serviceName = 'category'
const listToTree = (list, options = {}) => {
  const {
      idKey = 'id',
      parentKey = 'pid',
      childrenKey = 'children'
  } = options;

  const map = {};
  const roots = [];

  // 首先将所有项目映射到一个对象中
  for (const item of list) {
      map[item[idKey]] = {
          ...item,
          [childrenKey]: []
      };
  }

  // 构建树结构
  for (const item of list) {
      const node = map[item[idKey]];
      if (item[parentKey] === null || item[parentKey] === 0 || !map[item[parentKey]]) {
          // 如果没有父节点或父节点不存在，作为根节点
          roots.push(node);
      } else {
          // 将当前节点添加到父节点的children数组中
          map[item[parentKey]][childrenKey].push(node);
      }
  }

  // 递归排序函数
  const sortTreeNodes = (nodes) => {
      // 对当前层级节点按sort字段排序
      nodes.sort((a, b) => (a.sort || 0) - (b.sort || 0));
      // 递归对子节点进行排序
      nodes.forEach(node => {
          if (node[childrenKey] && node[childrenKey].length > 0) {
              sortTreeNodes(node[childrenKey]);
          }
      });
      return nodes;
  };

  // 对根节点及其所有子节点进行排序
  return sortTreeNodes(roots);
};

class RouterController extends Controller {
  // 分页
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize, name = '' } = query;
    let page = Number(pageNum) || 1;
    let size = Number(pageSize) || 10;
    const where = {

    };
    if (name) {
      where.name = { [Op.like]: `%${name}%` }
    }
    if (!isNaN(Number(query.status))) {
      where.status = query.status
    }
    const list = await service[serviceName].getPage(where, page, size);
    this.ctx.success(list);
  }
  // 新增
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service[serviceName].create(data);
    ctx.success(data, 200);
  }
  // 修改
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[serviceName].update(id, infos);
    ctx.success(id, 200);
  }
  // 删除
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[serviceName].deleteById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }
  // 查看
  async show() {
    const { params, service } = this.ctx;
    const findItem = await service[serviceName].findOne(params.id);
    this.ctx.success(findItem);
  }
  // 所有列表
  async allList() {
    const { service } = this.ctx;
    const list = await service[serviceName].allList();
    // 使用 dataValues 获取数据
    const plainList = list.map(item => item.get({ plain: true }));
    // 构建树形结构
    const tree = listToTree(plainList);
    // 返回树形结构
    this.ctx.success(tree);
  }
}

module.exports = RouterController;
